#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <cstring>
#include <cstdlib>

void ChildWrite(int wfd)
{
    char buffer[1024];
    int cnt = 0;
    while (true)
    {
        snprintf(buffer, sizeof(buffer), "I am child,pid: %d, cnt: %d", getpid(), cnt++);
        write(wfd, buffer, strlen(buffer));
        sleep(1);
    }
}

void FatherRead(int rfd)
{
    char buffer[1024];
    while (true)
    {
        memset(buffer, 0, sizeof(buffer));
        int n = read(rfd, buffer, sizeof(buffer)-1);
        if (n == -1)
        {
            std::cerr << "read error" << std::endl;
            break;
        }
        if (n == 0)
        {
            std::cout << "child process exited" << std::endl;
            break;
        }
        buffer[n] = '\0';
        std::cout << "read from pipe: " << buffer << std::endl;
    }
}








    int main()
 {
        int pipefd[2] = {0};
        if (pipe(pipefd) == -1)
        {

            std::cerr << "pipe error" << std::endl;
            return 1;
        }
        std::cout << "pipefd[0] = " << pipefd[0] << std::endl;
        std::cout << "pipefd[1] = " << pipefd[1] << std::endl;
        pid_t pid = fork();
        if (pid == -1)
        {
            std::cerr << "fork error" << std::endl;
            return 1;
        }

        if (pid == 0)
        {
            // child process
            close(pipefd[0]);
            // std::string str = "hello, world";
            // write(pipefd[1], str.c_str(), str.size() + 1);
            // close(pipefd[1]);
            ChildWrite(pipefd[1]);
            close(pipefd[1]);
            return 0;
        }
        else
        {
            // parent process
            close(pipefd[1]);
            // char buf[1024];
            // read(pipefd[0], buf, sizeof(buf));
            // std::cout << "read from pipe: " << buf << std::endl;
            FatherRead(pipefd[0]);
            close(pipefd[0]);
            return 0;
        }
    }